package com.cooper.controllers;

import javax.servlet.http.Cookie;

import org.springframework.beans.factory.annotation.Autowired;

import com.cooper.constants.ResourceConstants;
import com.cooper.core.JsonResult;
import com.cooper.core.OptionDo;
import com.cooper.entity.ResourceUsedEntity;
import com.cooper.resource.IResourceManager;
import com.cooper.service.admin.ResourceUsedService;
import com.cooper.util.ThreadUtils;
import com.google.common.base.Function;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;

public class InvitationController {
	
	@Autowired
	private IResourceManager resourceManager;
	
	@Autowired
	private ResourceUsedService resourceUsedService;
	
	@Get
	public String execute(Invocation inv) throws Exception{
		inv.addModel("testUserCount", this.resourceUsedService.queryUsedCount(ResourceConstants.ResourceUsedOrigin.WEB_INVITATION));
		return "invitation";
	}

	@Post("checkCode")
	public Object checkCode(Invocation inv, @Param("code") String code) throws Exception{
		JsonResult json = new JsonResult();
		OptionDo data = (OptionDo)this.resourceManager.getResItem(ResourceConstants.ResourceUsedOrigin.WEB_INVITATION, code);
		if(null != data){
			ResourceUsedEntity entity = new ResourceUsedEntity();
			entity.setOrigin(ResourceConstants.ResourceUsedOrigin.WEB_INVITATION);
			entity.setResourceCode(code);
			
			ThreadUtils.newThread(entity, new Function<ResourceUsedEntity, String>(){
				@Override
				public String apply(ResourceUsedEntity input) {
					try {
						if(!resourceUsedService.checkIfExists(ResourceConstants.ResourceUsedOrigin.WEB_INVITATION, input.getResourceCode())){
							resourceUsedService.saveEntity(input);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}
				
			});
			
		    inv.getResponse().addCookie(new Cookie("invitationCode", code));
			inv.getRequest().getSession().setAttribute("invitationCode", code);
			json.setSuccess(true);
		}
		return json;
	}
}
